﻿using System.Linq;
using Microsoft.AspNetCore.Mvc.Filters;
using ZilLion.Service.Crm.CommonRepository;
using ZilLion.Service.Crm.ModelBase.EntityBase.Data;
using ZilLion.Service.Crm.ModelBase.EntityBase.RedisEntity;
using ZilLion.Service.Crm.Unities.Other;

namespace ZilLion.Service.WebInfrastructure.Filter
{
    public class SplitDBAttribute :  ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            if (actionContext.HttpContext.Request.Headers.All(tr => tr.Key != "passport"))
            {
                WebApiBase apibase = actionContext.Controller as WebApiBase;
                apibase.SetAccid(null);
             
                base.OnActionExecuting(actionContext);
                return;
            }
            string Passport = actionContext.HttpContext.Request.Headers["passport"].FirstOrDefault();
            string PassportType = actionContext.HttpContext.Request.Headers["passporttype"].FirstOrDefault();
            //string PassportType = actionContext.Request.Headers.GetValues("passporttype").FirstOrDefault();
            if (string.IsNullOrEmpty(Passport) || string.IsNullOrEmpty(PassportType))
            {
                WebApiBase apibase = actionContext.Controller as WebApiBase;
                apibase.SetAccid(null);
                base.OnActionExecuting(actionContext);
                return;
            }
          
            //GloabAccidCacheLoader.CheckAccidCache();
            //查找缓存里的账号id进行HashCode
            string wxcardno=null;
            WebApiBase Apibase = actionContext.Controller as WebApiBase;
            if (PassportType == "-1")
            {
                Apibase.SetBaseInfo(0, Passport, PassportType, wxcardno);
                base.OnActionExecuting(actionContext);
                return;
            }
            if (PassportType == "6")
            {
                wxcardno=Passport;
                var sum = Passport.Substring(Passport.Length - 1, 1);
                Passport = Passport.Substring(0, Passport.Length - 1);
                string sumstr = CodeValidate.GetValidatecode(Passport);
                Passport = Passport.Substring(2);
                if (sum != sumstr)
                {
                    throw new System.Exception("校验未通过！" + actionContext.HttpContext.Request.Path.Value);
                }
            }
            AccidModel accid = AccidHelper.GetAccid(PassportType, Passport);
            if (accid.accid == 0)
            {
                throw new System.Exception("错误码1404:账号无法找到！" + Passport + "," + PassportType + "," + @"请按下列步骤排查：1、请确认该卡是否已售出，未售出则无法查询；2、如该卡刚售出，请及时上传数据，10分钟后再查询；3、如该卡为黑名单卡（已被换卡或注销），则无法查询。如仍有问题，请联系客服处理，谢谢！");
                //throw new Exception("账号无法找到！" + Passport + "," + PassportType + ',' + actionContext.Request.RequestUri.AbsoluteUri);
            }
            if (string.IsNullOrEmpty(accid.openid))
            {
                Apibase.SetOpenid("");
            }
            else
            {
                Apibase.SetOpenid(accid.openid);
            }
            Apibase.SetBaseInfo(accid.accid, Passport, PassportType, wxcardno);
            var item = SqlConnectionLoader.ReadDbContextList.Cast<IMultiDbContext>()
            .FirstOrDefault(tr => tr.mikey== accid.ConstrName);
            if(item!=null) Apibase.SetDbContext(item);
           
            if (!actionContext.HttpContext.Request.Headers.ContainsKey("passport1") ||
                !actionContext.HttpContext.Request.Headers.ContainsKey("passporttype1"))
            {
                base.OnActionExecuting(actionContext);
                return;
            }
            string wxcardno1 = null;
            string Passport1 = actionContext.HttpContext.Request.Headers["passport1"].FirstOrDefault();
            string PassportType1 = actionContext.HttpContext.Request.Headers["passporttype1"].FirstOrDefault();
            if (!string.IsNullOrEmpty(Passport1)&& !string.IsNullOrEmpty(PassportType1))
            {
                if (PassportType1 == "6")
                {
                    wxcardno1 = Passport1;
                    var sum = Passport1.Substring(Passport1.Length - 1, 1);
                    Passport1 = Passport1.Substring(0, Passport1.Length - 1);
                    string sumstr = CodeValidate.GetValidatecode(Passport1);
                    Passport1 = Passport1.Substring(2);
                    if (sum != sumstr)
                    {
                        throw new System.Exception("校验未通过！" + actionContext.HttpContext.Request.Path.Value);
                    }
                }
                AccidModel accid1 = AccidHelper.GetAccid(PassportType1, Passport1);
                if (accid1.accid == 0)
                {
                    throw new System.Exception("错误码1404:账号无法找到！" + Passport + "," + PassportType + "," + @"请按下列步骤排查：1、请确认该卡是否已售出，未售出则无法查询；2、如该卡刚售出，请及时上传数据，10分钟后再查询；3、如该卡为黑名单卡（已被换卡或注销），则无法查询。如仍有问题，请联系客服处理，谢谢！");
                    //throw new Exception("账号无法找到！" + actionContext.Request.RequestUri.AbsoluteUri);
                }
                Apibase.SetBaseInfo1(accid1.accid, Passport1, PassportType1, wxcardno1);
                var item1 = SqlConnectionLoader.ReadDbContextList.Cast<IMultiDbContext>()
                .FirstOrDefault(tr => tr.mikey == accid1.ConstrName);
                if (item1 != null) Apibase.SetDbContext1(item1);
            }
            base.OnActionExecuting(actionContext);
        }
    }
}


